//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.bootdo.clouddo.advice;

import com.bootdo.clouddo.utils.rsa.Base64Util;
import com.bootdo.clouddo.utils.rsa.RSAUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class DecryptHttpInputMessage implements HttpInputMessage {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private HttpHeaders headers;
    private InputStream body;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset) throws Exception {
        if (StringUtils.isEmpty(privateKey)) {
            throw new IllegalArgumentException("privateKey is null");
        } else {
            this.headers = inputMessage.getHeaders();
            String content = (String)(new BufferedReader(new InputStreamReader(inputMessage.getBody()))).lines().collect(Collectors.joining(System.lineSeparator()));
            String decryptBody;
//            if (content.startsWith("{")) {
//                this.log.info("Unencrypted without decryption:{}", content);
//                decryptBody = content;
//            } else {
//
//            }
            StringBuilder json = new StringBuilder();
            content = content.replaceAll(" ", "+");
            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split("\\|");
                String[] var8 = contents;
                int var9 = contents.length;

                for(int var10 = 0; var10 < var9; ++var10) {
                    String value = var8[var10];
                    value = new String(RSAUtil.decrypt(Base64Util.decode(value), privateKey), charset);
                    json.append(value);
                }
            }

            decryptBody = json.toString();
            this.log.info("Encrypted data received：{},After decryption：{}", content, decryptBody);

            this.body = new ByteArrayInputStream(decryptBody.getBytes());
        }
    }

    public InputStream getBody() {
        return this.body;
    }

    public HttpHeaders getHeaders() {
        return this.headers;
    }
}
